package com.knife.news.manage.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.knife.news.logic.FieldsService;
import com.knife.news.logic.FormService;
import com.knife.news.logic.NewsService;
import com.knife.news.logic.RelativeService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.Type2Service;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.FieldsServiceImpl;
import com.knife.news.logic.impl.FlowNodeServiceImpl;
import com.knife.news.logic.impl.FlowServiceImpl;
import com.knife.news.logic.impl.FormServiceImpl;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.RelativeServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.Type2ServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.model.Fields;
import com.knife.news.model.Form;
import com.knife.news.object.Flow;
import com.knife.news.object.FlowNode;
import com.knife.news.object.FormField;
import com.knife.news.object.Logs;
import com.knife.news.object.News;
import com.knife.news.object.Relative;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.news.object.Type2;
import com.knife.news.object.User;
import com.knife.util.CommUtil;
import com.knife.web.ActionContext;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class NewsManageAction extends ManageAction {
	private SiteService siteDAO = SiteServiceImpl.getInstance();
	private NewsService newsDAO = NewsServiceImpl.getInstance();
	private TypeService typeDAO = TypeServiceImpl.getInstance();
	private Type2Service type2DAO = Type2ServiceImpl.getInstance();
	private FormService formDAO = FormServiceImpl.getInstance();
	private FieldsService fieldsDAO = FieldsServiceImpl.getInstance();
	private RelativeService relativeDAO = RelativeServiceImpl.getInstance();
	private Type thisType = new Type();
	private Type aType;
	private String tid = "";
	private String sid = "";
	private String treenews = "";
	private int isaudit=-1;
	private Date nowDate=new Date();
	
	//
	private FlowServiceImpl flowDao=FlowServiceImpl.getInstance();
	private FlowNodeServiceImpl flowNodeDao = FlowNodeServiceImpl.getInstance();
	private String flow;
	private String node;

	public Page doInit(WebForm form, Module module) {
		return module.findPage("index");
	}

	public Page doTree(WebForm form, Module module) {
		String tree_id = CommUtil.null2String(form.get("tree_id"));
		String treenews = CommUtil.null2String(form.get("treenews"));
		form.addResult("tree_id", tree_id);
		form.addResult("treenews", treenews);
		return module.findPage("tree");
	}

	public Page doList(WebForm form, Module module) {
		if(form.get("isaudit")!=null){
			isaudit=Integer.parseInt(form.get("isaudit").toString());
		}
		if (tid.equals("")) {
			tid = CommUtil.null2String(form.get("tid"));
		}
		if (sid.equals("")) {
			sid = CommUtil.null2String(form.get("sid"));
		}
		if (treenews.equals("")) {
			treenews = CommUtil.null2String(form.get("treenews"));
		}
		if (popedom <2) {
			if (!typeDAO.hasRightUser(tid, user.getId(),popedom)) {
				//jlm -workflow
				
//				Collection<Object> paras= new ArrayList<Object>();
//				String sql = "k_status=? order by k_date asc";
//				
//				List<Flow> flowlist= new ArrayList<Flow>();
//				paras.add(1);
//				flowlist= flowDao.getFlowBySql(sql, paras, 0, -1);
//				for(int i=0;flowlist!=null && i<flowlist.size();i++){
//					List<FlowNode> nodelist = new ArrayList<FlowNode>();
//					nodelist = flowNodeDao.getFlowNodeByFlowId(flowlist.get(i).getId());
//					if(nodelist!=null){
//						//form.addResult("", s);
//					}
//				}
				//end workflow
				return new Page("noright", "/user_index.html");
			}
		}
		String addCondition = "";
		String key_words = CommUtil.null2String(form.get("key_words"));
		if (key_words.length() > 0) {
			addCondition = " and (id='"+key_words+"' or k_title like '%" + key_words
					+ "%' or k_content like '%" + key_words + "%')";
		}
		if(sid.length()>0){
			addCondition += " and k_type in(select id from k_type where k_site='"+sid+"')";
		}
		if (tid.length() > 0) {
			addCondition += " and k_type='" + tid + "'";
			form.addResult("tid", tid);
			try{
				thisType = typeDAO.getTypeById(tid);
				if(sid.length()<=0){
					sid=thisType.getSite();
				}
			}catch(Exception e){}
			form.addResult("thisType", thisType);
			form.addResult("sid", sid);
		}else{
			tid="0";
			addCondition += " and k_type='0'";
			form.addResult("tid", tid);
		}
		if(isaudit>=0){
			addCondition += " and k_display=" + isaudit;
			form.addResult("isaudit", isaudit);
		}
		if (treenews.length() > 0) {
			addCondition += " and k_treenews='" + treenews + "'";
			form.addResult("treenews", treenews);
		}
		//System.out.println("生成的查询是:"+addCondition);
		//List<News> allNews = newsDAO.getNews("id!=''" + addCondition);
		//int rows = allNews.size();// 分页开始
		int rows = newsDAO.getSum(-1, "",sid, tid, key_words, "", "");
		int pageSize = 15;
		int currentPage = 1;
		int frontPage = 0;
		int nextPage = currentPage + 1;
		List<News> firstNews = new ArrayList<News>();
		int totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));
		String orderby=" order by length(k_order) desc,k_order desc";
		if(thisType.getOrderby()!=null){
		switch(thisType.getOrderby()){
			case "pubdatedesc":
				orderby=" order by k_date desc";
				break;
			case "pubdate":
				orderby=" order by k_date";
				break;
			case "titledesc":
				orderby=" order by k_title desc";
				break;
			case "title":
				orderby=" order by k_title";
				break;
			default:
				orderby=" order by length(k_order) desc,k_order desc";
		}
		}
		firstNews = newsDAO.getNewsBySql("id!=''" + addCondition + orderby, null, 0, pageSize);
		form.addResult("key_words", key_words);
		form.addResult("rows", rows);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("currentPage", currentPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("newsList", firstNews);
		return module.findPage("list");
	}

	public Page doPage(WebForm form, Module module) {
		if(form.get("isaudit")!=null){
			isaudit=Integer.parseInt(form.get("isaudit").toString());
		}
		if (tid.equals("")) {
			tid = CommUtil.null2String(form.get("tid"));
		}
		if (sid.equals("")) {
			sid = CommUtil.null2String(form.get("sid"));
		}
		if (treenews.equals("")) {
			treenews = CommUtil.null2String(form.get("treenews"));
		}
		if (popedom<2) {
			if (!typeDAO.hasRightUser(tid, user.getId(),popedom)) {
				return new Page("noright", "/user_index.html");
			}
		}
		String addCondition = "";
		String key_words = CommUtil.null2String(form.get("key_words"));
		if (key_words.length() > 0) {
			addCondition = " and (id='"+key_words+"' or k_title like '%" + key_words
					+ "%' or k_content like '%" + key_words + "%')";
		}
		if(sid.length()>0){
			addCondition += " and k_type in(select id from k_type where k_site='"+sid+"')";
		}
		if (tid.length() > 0) {
			addCondition += " and k_type='" + tid + "'";
			form.addResult("tid", tid);
			try{
				thisType = typeDAO.getTypeById(tid);
				if(sid.length()<=0){
					sid=thisType.getSite();
				}
			}catch(Exception e){}
			form.addResult("thisType", thisType);
			form.addResult("sid", sid);
		}else{
			tid="0";
			addCondition += " and k_type='0'";
			form.addResult("tid", tid);
		}
		if(isaudit>=0){
			addCondition += " and k_display=" + isaudit;
			form.addResult("isaudit", isaudit);
		}
		if (treenews.length() > 0) {
			addCondition += " and k_treenews='" + treenews + "'";
			form.addResult("treenews", treenews);
		}
		//List<News> allNews = newsDAO.getNews("id!=''" + addCondition);
		//int rows = allNews.size();
		int rows = newsDAO.getSum(-1, "",sid, tid, key_words, "", "");
		int pageSize = 15;
		int paraPage = CommUtil.null2Int(form.get("page"));
		int frontPage = paraPage - 1;
		int nextPage = paraPage + 1;
		int totalPage = (int) Math.ceil((float) rows / (float) pageSize);
		int begin = (paraPage - 1) * pageSize + 1;
		int end = rows - begin + 1;
		List<News> newsList = new ArrayList<News>();
		/*
		 * if (frontPage <= 0) { frontPage=1; form.addResult("msg", "这是第一页了！");
		 * } if (nextPage >= totalPage+1) { nextPage=totalPage;
		 * form.addResult("msg", "这是最后一页了！"); }
		 */
		form.addResult("keywords", key_words);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("nextPage", nextPage);
		String orderby=" order by length(k_order) desc,k_order desc";
		if(thisType.getOrderby()!=null){
		switch(thisType.getOrderby()){
			case "pubdatedesc":
				orderby=" order by k_date desc";
				break;
			case "pubdate":
				orderby=" order by k_date";
				break;
			case "titledesc":
				orderby=" order by k_title desc";
				break;
			case "title":
				orderby=" order by k_title";
				break;
			default:
				orderby=" order by length(k_order) desc,k_order desc";
		}
		}
		if (end < pageSize) {
			newsList = newsDAO.getNewsBySql("id!=''" + addCondition
					+ orderby, null,
					begin - 1, end);
		} else {
			newsList = newsDAO.getNewsBySql("id!=''" + addCondition
					+ orderby, null,
					begin - 1, pageSize);
		}
		form.addResult("currentPage", paraPage);
		form.addResult("totalPage", totalPage);
		form.addResult("rows", rows);
		form.addResult("newsList", newsList);
		return module.findPage("list");
	}

	public Page doDisplay(WebForm form, Module module) {
		String id = (String) form.get("id");
		News news = newsDAO.getNewsById(id);
		news.setDisplay(1);
		newsDAO.updateNews(news);
		form.addResult("msg", "通过审核！");
		news.updatePub();
		/*
		tid = news.getType();
		Site site = siteDAO.getSite();
		if (site.getHtml() > 0) {
			HTMLGenerater generater = new HTMLGenerater(site.getId());
			generater.saveTypeIndexToHtml(tid);
		}
		*/
		return doEdit(form, module);
	}

	public Page doNoDisplay(WebForm form, Module module) {
		String id = (String) form.get("id");
		News news = newsDAO.getNewsById(id);
		news.setDisplay(0);
		newsDAO.updateNews(news);
		form.addResult("msg", "取消审核！");
		news.updatePub();
		/*
		tid = news.getType();
		Site site = siteDAO.getSite();
		if (site.getHtml() > 0) {
			HTMLGenerater generater = new HTMLGenerater(site.getId());
			generater.saveTypeIndexToHtml(tid);
			generater.saveIndexToHtml();
		}
		*/
		Logs log=new Logs("["+user.getUsername()+"]" + "撤销文章:"+news.getTitle());
		logDAO.saveLogs(log);
		return doEdit(form, module);
	}

	private boolean deleteNews(News news) {
		//更新文章下线
		news.delLine();
		//删除引用文章
		List<News> linkNews=news.getLinkedNews();
		if(linkNews.size()>0){
			for(News anews:linkNews){
				anews.delLine();
				newsDAO.delNews(anews);
			}
		}
		//删除相关文章
		Relative rel=relativeDAO.getRelativeByNewsId(news.getId());
		if(rel!=null){
			relativeDAO.delRelative(rel);
		}
		// System.out.println("删除附件！");
		// 先删除文章中的附件
		if (news.getFile() != null) {
			String attachFile = news.getFile();
			if (attachFile.length() > 0) {
				// String filePath=attachFile.substring(1).replace("/",
				// File.separator);
				String filePath = Globals.APP_BASE_DIR
						+ attachFile.substring(1).replace("/", File.separator);
				File f = new File(filePath);
				if (f.exists()) {
					f.delete();
				}
			}
		}
		// 删除自定义字段
		Type aType = typeDAO.getTypeById(news.getType());
		if(aType!=null){
		if (aType.getForm() != null) {
			String formId = aType.getForm();
			Form aform = formDAO.getFormById(formId);
			if (aform != null) {
				// System.out.println("取得的表单ID是:"+ids[i]);
				List<FormField> formFields = fieldsDAO.jsonStringToList(
						news.getId(), aform.getContent());
				for (FormField formField : formFields) {
					Fields afield = fieldsDAO.getFieldsByNews(news.getId(),
							formField.getOrder());
					fieldsDAO.delFields(afield);
				}
				// form.addResult("fieldList", formFields);
			}
		}
		}
		// System.out.println("文章附属删除完毕！");
		//记录日志
		Logs log=new Logs("["+user.getUsername()+"]删除文章:"+news.getTitle());
		logDAO.saveLogs(log);
		// 再删除本文章
		return newsDAO.delNews(news);
	}

	public Page doDelete(WebForm form, Module module) {
		String id = CommUtil.null2String(form.get("id"));
		boolean result = false;
		//System.out.println("获取到的ID是:" + id);
		if (id.indexOf(",") > 0) {
			String[] ids = id.split(",");
			for (int i = 0; i < ids.length; i++) {
				News news = newsDAO.getNewsById(ids[i]);
				tid = news.getType();
				result = deleteNews(news);
			}
		} else {
			News news = newsDAO.getNewsById(id);
			tid = news.getType();
			result = deleteNews(news);
		}
		if (result) {
			form.addResult("msg", "删除成功！");
			return doList(form, module);
		} else {
			form.addResult("msg", "删除失败！");
			return doList(form, module);
		}
	}

	public Page doAdd(WebForm form, Module module) {
		tid = CommUtil.null2String(form.get("tid"));
		treenews = CommUtil.null2String(form.get("treenews"));
		List<Type> typeList = new LinkedList<Type>();
		List<Type2> type2List = type2DAO.getAllTypes();
		if (!tid.equals("")) {
			// 输出自定义表单
			Type aType = typeDAO.getTypeById(tid);
			if(aType.getSite()!=null){
				Site site = siteDAO.getSiteById(aType.getSite());
				if(site!=null){
					//form.addResult("sid", aType.getSite());
					if(site.getHtml()==1){
						//ActionContext.getContext().getSession().removeAttribute("site_dir");
						ActionContext.getContext().getSession().setAttribute("site_dir", site.getPub_dir());
						if(site.getBig5()==1){
							//ActionContext.getContext().getSession().removeAttribute("big5_dir");
							ActionContext.getContext().getSession().setAttribute("big5_dir", site.getPub_dir()+"/big5");
						}
					}
					form.addResult("thisSite", site);
				}
			}
			if (popedom > 0) {
				typeList = typeDAO.getSubTypesById(aType.getParent());
			} else {
				typeList = typeDAO.getRightSubTypesById(aType.getParent(),
						user.getId());
			}
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+ids[i]);
						List<FormField> formFields = fieldsDAO.jsonStringToList("0", aform.getContent());
						form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			form.addResult("tid", tid);
			form.addResult("tname", aType.getName());
		}
		form.addResult("action", "save");
		form.addResult("treenews", treenews);
		form.addResult("typeList", typeList);
		form.addResult("type2List", type2List);
		form.addResult("user", user);
		return module.findPage("edit");
	}

	public Page doSave(WebForm form, Module module) {
		String id ="";
		String linkTypes = CommUtil.null2String(form.get("linkTypes"));
		String otherTypes = CommUtil.null2String(form.get("otherTypes"));
		String date = CommUtil.null2String(form.get("date"));
		String offdate = CommUtil.null2String(form.get("offdate"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = sdf.parse(date);
		} catch (Exception e) {
			startDate = nowDate;
		}
		try{
			endDate = sdf.parse(offdate);
		}catch(Exception e){
			endDate = null;
			//GregorianCalendar gc =new GregorianCalendar();
			//gc.setTime(startDate);
			//gc.add(1, 10);
			//endDate = gc.getTime();
		}
		News fnews = (News) form.toPo(News.class);
		fnews.setDate(startDate);
		fnews.setOffdate(endDate);
		//检查用户身份并附权限
		
		// 首先先判断下是否使用了发文工作流并查看工作流是否已啟動
		if (user.getPopedom() !=1) {// 只在编辑文章时才创建文章审核需要的人，fnews.setFlowusers
			Type type = typeDAO.getTypeById(fnews.getType());
			if (type.getFlow() != null && type.getFlow() != ""
					&& flowDao.getFlowById(type.getFlow()) != null
					&& flowDao.getFlowById(type.getFlow()).getStatus() == 1) {
				List<FlowNode> nodelist = new ArrayList<FlowNode>();
				nodelist = flowNodeDao.getFlowNodeByFlowId(type.getFlow());
				for (int i = 0; nodelist != null && i < nodelist.size(); i++) {
					if (nodelist.get(i).getType() == 2 && nodelist.get(i).getExecute_type()==2) {// 2表示审核文章 ，1表示编辑文章
						int pop = CommUtil.null2Int(nodelist.get(i)
								.getExecutor());
						String sql = "k_popedom=1";
						List<User> userlist = userDAO.getUsersBySql(sql);
						String userid = "";
						for (int j = 0; userlist != null && j < userlist.size(); j++) {
							userid += userlist.get(j).getId().toString() + ",";
						}
						fnews.setFlowusers(userid);
					}
				}
			}
		}
		if (user.getPopedom() == 1) {

			// workflow
			Type type = typeDAO.getTypeById(fnews.getType());
			if (type.getFlow() != null && type.getFlow() != ""
					&& flowDao.getFlowById(type.getFlow()) != null
					&& flowDao.getFlowById(type.getFlow()).getStatus() == 1) {
				List<FlowNode> nodelist1 = new ArrayList<FlowNode>();
				nodelist1 = flowNodeDao.getFlowNodeByFlowId(type.getFlow());
				for (int i = 0; nodelist1 != null && i < nodelist1.size(); i++) {
					int lei=nodelist1.get(i).getType();
					if (nodelist1.get(i).getType() == 2) {
						if (nodelist1.get(i).getExecute_type() == 1) {
							fnews.setDisplay(1);
						} else {
							if (nodelist1.get(i).getExecute_type() == 2) {
								// 怎么实现所有人都审核过，文章才算审核 了呢？？？？？
							
								String ids = fnews.getFlowusers();
								String[] uid = ids.split(",");
								String latest = "";
								for (int k = 0; uid != null && k < uid.length; k++) {
									if (uid[k] != user.getId()) {
										latest += uid[k] + ",";
									}
								}
								fnews.setFlowusers(latest);
								if (latest == "") {
									fnews.setDisplay(1);
									form.addResult("msg", "该文章审核成功！");
								} else {

									form.addResult("msg",
											"本次审核成功，但还需要其他人的审核才能最终审核该文章！");
								}
								
							}
						}// end else
					}
				}

			} else {
				fnews.setDisplay(1);
			}

			// end workflow
			// fnews.setDisplay(1);
		}
		id = newsDAO.addNews(fnews);
		
		tid = fnews.getType();
		News news=new News();
		if (id.length()>0) {
			//news.setId(id);
			news=newsDAO.getNewsById(id);
			// 保存自定义表单
			aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+ids[i]);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						saveUserForm(form, formFields, formId, news.getId());
						// form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			// 新闻的引用
			if (!linkTypes.equals("")) {
				String[] typeids = linkTypes.split(",");
				for (int i = 0; i < typeids.length; i++) {
					News anew = new News();
					anew.setTitle(news.getTitle());
					// anew.setFile(news.getFile());
					anew.setLink(news.getId());
					anew.setType(typeids[i]);
					anew.setContent("<p>&nbsp;</p>");
					anew.setCommend("0");
					anew.setDisplay(news.getDisplay());
					anew.setDate(news.getDate());
					newsDAO.saveNews(anew);
				}
			}
			if(aType!=null){
				news.updatePub();
			}
			// 新闻的分发
			if (!otherTypes.equals("")) {
				String[] typeids = otherTypes.split(",");
				for (int i = 0; i < typeids.length; i++) {
					News anew = news;
					com.knife.news.model.News bnews = new com.knife.news.model.News();
					anew.setId(bnews.getId());
					anew.setType(typeids[i]);
					//News anew = new News(bnews);
					addNews(anew, form);
				}
			}
			//workflow
			//end workflow
			form.addResult("msg", "发布成功！");
		} else {
			form.addResult("msg", "发布失败,请检查权限和日志！");
		}
		return doList(form, module);
	}

	private void foreach(Object auser) {
		// TODO Auto-generated method stub
		
	}

	private Object auser(List<User> userlist) {
		// TODO Auto-generated method stub
		return null;
	}

	private boolean addNews(News news, WebForm form) {
		String logstr="保存";
		if(user.getPopedom()==0){
			logstr="保存";
		}else if(user.getPopedom()==1){
			logstr="审核";
		}else{
			logstr="发布";
		}
		boolean ret = newsDAO.saveNews(news);
		if (ret) {
			// System.out.println("在保存之后ID是否已生成："+news.getId());
			// 保存自定义表单
			Type aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					Form aform = formDAO.getFormById(formId);
					// System.out.println("取得的表单ID是:"+ids[i]);
					List<FormField> formFields = fieldsDAO.jsonStringToList(
							news.getId(), aform.getContent());
					saveUserForm(form, formFields, formId, news.getId());
					// form.addResult("fieldList", formFields);
				}
			}
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+ logstr + "文章:"+news.getTitle());
			logDAO.saveLogs(log);
		}else{
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+ logstr + "文章失败:"+news.getTitle());
			logDAO.saveLogs(log);
		}
		return ret;
	}

	public Page doEdit(WebForm form, Module module) {
		String id = CommUtil.null2String(form.get("id"));
		News news = newsDAO.getNewsById(id);
		List<Type> typeList = new LinkedList<Type>();
		List<Type2> type2List = type2DAO.getAllTypes();
		tid = CommUtil.null2String(news.getType());
		//System.out.println("取得的类别ID是:"+tid);
		if (!tid.equals("") && tid.indexOf(",") < 0) {
			Type aType = typeDAO.getTypeById(tid);
			if(aType!=null){
			if(aType.getSite()!=null){
				Site site = siteDAO.getSiteById(aType.getSite());
				if(site!=null){
					//form.addResult("sid", aType.getSite());
					if(site.getHtml()==1){
						ActionContext.getContext().getSession().setAttribute("site_dir", site.getPub_dir());
						if(site.getBig5()==1){
							ActionContext.getContext().getSession().setAttribute("big5_dir", site.getPub_dir()+"/big5");
						}
					}
					form.addResult("thisSite", site);
				}
			}
			if (popedom > 0) {
				typeList = typeDAO.getSubTypesById(aType.getParent());
			} else {
				typeList = typeDAO.getRightSubTypesById(aType.getParent(),
						user.getId());
			}
			form.addResult("tid", tid);
			form.addResult("tname", aType.getName());
			// 取得自定义表单
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+formId);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			}else{
				form.addResult("tname", "无频道");
			}
		}
		form.addResult("action", "update");
		form.addResult("news", news);
		form.addResult("typeList", typeList);
		form.addResult("type2List", type2List);
		if (news.getLink() != null) {
			return module.findPage("link");
		} else {
			return module.findPage("edit");
		}
	}

	public Page doUpdate(WebForm form, Module module) {
		News news = (News) form.toPo(News.class);
		String date = CommUtil.null2String(form.get("date"));
		String offdate = CommUtil.null2String(form.get("offdate"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = sdf.parse(date);
		} catch (Exception e) {
			startDate = nowDate;
		}
		try{
			endDate = sdf.parse(offdate);
		}catch(Exception e){
			endDate = null;
			//GregorianCalendar gc =new GregorianCalendar();
			//gc.setTime(startDate);
			//gc.add(1, 10);
			//endDate = gc.getTime();
		}
		news.setDate(startDate);
		if(endDate!=null){
			news.setOffdate(endDate);
		}
		tid = news.getType();
		form.addResult("tid", tid);
		//检查用户身份并附权限
		int flowflag=0;
		int p = user.getPopedom();
		if (user.getPopedom() == 1) {
			// flow
			if (news.getDisplay() == 1) {
				Collection<Object> pa = new ArrayList<Object>();
				String sqlflow = "";
				pa.add(typeDAO.getTypeById(tid).getFlow());
				sqlflow = "id=? and k_status='1'";
				if (flowDao.getFlowBySql(sqlflow, pa, 0, -1).size() > 0) {
					List<FlowNode> nodelist1 = new ArrayList<FlowNode>();
					nodelist1 = flowNodeDao.getFlowNodeByFlowId(typeDAO
							.getTypeById(tid).getFlow());
					for (int i = 0; nodelist1 != null && i < nodelist1.size(); i++) {
						int lei = nodelist1.get(i).getType();
						if (nodelist1.get(i).getType() == 2) {
							if (nodelist1.get(i).getExecute_type() == 1) {
								news.setDisplay(1);
							} else {
								if (nodelist1.get(i).getExecute_type() == 2) {
									// 怎么实现所有人都审核过，文章才算审核 了呢？？？？？

									String ids = news.getFlowusers();
									String[] uid = ids.split(",");
									String latest = "";
									for (int k = 0; uid != null
											&& k < uid.length; k++) {
										String userid = user.getId();
										if (!uid[k].equals(user.getId())) {
											latest += uid[k] + ",";
										}
									}
									news.setFlowusers(latest);
									if (latest == "") {
										news.setDisplay(1);
										form.addResult("msg", "该文章审核成功！");
									} else {
										news.setDisplay(0);
										form.addResult("msg",
												"本次审核成功，但还需要其他人的审核才能最终审核该文章！");
										flowflag = 1;
									}

								}
							}// end else
						}
					}

				} else {
					news.setDisplay(1);
				}
			}
			// end flow
			// news.setDisplay(1);
		}
		if (newsDAO.updateNews(news)) {
			//保存自定义表单
			Type aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+formId);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						updateUserForm(form, formFields, formId, news.getId());
						// form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			//生成html页面
			news.updatePub();
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+"编辑文章:"+news.getTitle());
			logDAO.saveLogs(log);
			if(flowflag==0){
			form.addResult("msg", "更新成功！");
			}else{
				form.addResult("msg", "本次审核成功，但还需要其他人的审核才能最终审核该文章！");
			}
		} else {
			Logs log=new Logs("["+user.getUsername()+"]"+"编辑文章失败:"+news.getTitle());
			logDAO.saveLogs(log);
			form.addResult("msg", "更新失败！");
		}
		return doList(form, module);
	}

	public Page doCommend(WebForm form, Module module) {
		String id = (String) form.get("id");
		News news = newsDAO.getNewsById(id);
		news.setCommend("1");
		newsDAO.updateNews(news);
		form.addResult("msg", "推荐成功！");
		tid = news.getType();
		news.updatePub();
		return doList(form, module);
	}

	public Page doNoCommend(WebForm form, Module module) {
		String id = (String) form.get("id");
		News news = newsDAO.getNewsById(id);
		news.setCommend("0");
		newsDAO.updateNews(news);
		form.addResult("msg", "取消推荐！");
		tid = news.getType();
		news.updatePub();
		return doList(form, module);
	}

	public News form2Obj(WebForm form) {
		String id = CommUtil.null2String(form.get("id"));
		News obj = newsDAO.getNewsById(id);
		if (obj == null) {
			obj = new News();
		}
		form.toPo(obj);
		return obj;
	}

	private void saveUserForm(WebForm form, List<FormField> formFields,
			String formid, String newsid) {
		for (FormField formField : formFields) {
			// FormField formField = formFields.get(i);
			/*
			 * if(formField.getType().equals("file")){ form =
			 * uploadFile(form,"u_"
			 * +formField.getName(),"upload_"+formField.getName()); }
			 */
			Fields afield = new Fields();
			afield.setFormid(formid);
			afield.setName(formField.getName());
			afield.setNewsid(newsid);
			afield.setOrder(formField.getOrder());
			afield.setValue(CommUtil.null2String(form.get("u_"
					+ formField.getName())));
			fieldsDAO.saveFields(afield);
			//System.out.println("成功添加字段值:"+formField.getName());
		}
	}

	private void updateUserForm(WebForm form, List<FormField> formFields,
			String formid, String newsid) {
		for (FormField formField : formFields) {
			Fields afield = fieldsDAO.getFieldsByNews(newsid,
					formField.getOrder());
			/*
			 * if(formField.getType().equals("file")){ form =
			 * uploadFile(form,"u_"
			 * +formField.getName(),"upload_"+formField.getName()); }
			 */
			if (afield != null) {
				afield.setFormid(formid);
				afield.setName(formField.getName());
				afield.setNewsid(newsid);
				afield.setOrder(formField.getOrder());
				afield.setValue(CommUtil.null2String(form.get("u_"
						+ formField.getName())));
				fieldsDAO.updateFields(afield);
			} else {
				afield = new Fields();
				afield.setFormid(formid);
				afield.setName(formField.getName());
				afield.setNewsid(newsid);
				afield.setOrder(formField.getOrder());
				afield.setValue(CommUtil.null2String(form.get("u_"
						+ formField.getName())));
				fieldsDAO.saveFields(afield);
			}
			//System.out.println("成功更新字段值:" + formField.getName() + ";字段的值是:"+ form.get("u_" + formField.getName()));
		}
	}
}
